import React, { useState } from 'react';
import CommonLayout from '../../../components/shop/common-layout';
import { Container, Row, Form, Input, Col } from 'reactstrap';
import { toast } from "react-toastify";
import { changePassword, getEmailReVerify } from '../../../api/api';
import { useRouter } from 'next/router';

const ForgetPwd = () => {
    const secondsRemaining = 60;
    const [formData, setFormData] = useState({
        "email": "",
        "password": "",
        "verifyCode": ""
    });
    const [verifyCodeBtn, setVerifyCodeBtn] = useState("Send Code");
    const [countDown, setCountDown] = useState(60);
    const [codeSended, setCodeSended] = useState(false);
    const router = useRouter();

    const submitOnClick = () => {
        if (formData.email == "" || formData.password == "" || formData.verifyCode == "") {
            toast.warning("Input Is Empty!")
        }
        else {
            changePassword(formData).then(res => {
                if (res.error_code == 2000) {
                    toast.success("Password changed successfully!");
                    localStorage.removeItem("XYCLogin");
                    router.push("/page/account/login");
                }
                else {
                    toast.warning("Password changed failed!");
                }
            });
        }
    }

    // 处理表单输入变化  
    const handleInputChange = (e) => {
        setFormData({ ...formData, [e.target.name]: e.target.value });
    };

    const UpdateCountDown = (secondsRemaining) => {
        // 显示倒数到控制台或页面上的元素
        // 如果倒数未完成则继续倒数
        if (secondsRemaining > 0) {
            // 递归调用updateCountdown，每隔1000毫秒（即1秒）递减一次
            setTimeout(UpdateCountDown, 1000, secondsRemaining - 1);
            setCountDown(secondsRemaining - 1);
        }
        else {
            setVerifyCodeBtn("Send Code");
            setCountDown(60);
            setCodeSended(false);
        }
    }

    // 发送邮箱验证码
    const VerifyBtnOnclick = () => {
        if (!codeSended && formData.email !== "") {
            var input = { emailAdress: formData.email };
            getEmailReVerify(input).then(res => {
                if (res.error_code == "2000") {
                    toast.success(res.msg);
                    setVerifyCodeBtn("Resend");
                    UpdateCountDown(secondsRemaining);
                    setCodeSended(true);
                }
                else {
                    toast.warning(res.msg);
                }
            });
        }
        else if (formData.email == "") {
            toast.warning("Please Enter Your Email.");
        }
    }

    return (
        <CommonLayout parent="home" title="Forget Password">
            <section className="pwd-page section-b-space">
                <Container>
                    <Row>
                        <Col lg="6" className="m-auto">
                            <h2>Forget Your Password</h2>
                            <Form className="theme-form">
                                <Row>
                                    <Col md="12">
                                        <Input type="text" className="form-control" id="email" name='email' onChange={handleInputChange} placeholder="Enter Your Email"
                                            required="" />
                                    </Col>
                                    <Col md="12">
                                        <Input type="password" className="form-control" id="password" name='password' onChange={handleInputChange} placeholder="password between 8 and 18 digits"
                                            required="" />
                                    </Col>
                                    <Col md="6">
                                        <div style={{ display: 'flex' }}>
                                            <Input type="text" className="form-control" id="verifyCode" name='verifyCode' placeholder="Verify Code"
                                                required="" onChange={handleInputChange} />
                                        </div>
                                    </Col>
                                    <Col md="6">
                                        <button type="button" onClick={VerifyBtnOnclick} className="btn-blank" style={{ height: 45, color: codeSended ? 'gray' : 'black', cursor: codeSended ? 'default' : 'cursor' }}>{verifyCodeBtn} {codeSended && countDown}</button>
                                    </Col>
                                    <Col md="12">
                                        <a href="#" className="btn btn-solid" style={{ width: 200 }} onClick={submitOnClick}>Submit</a>
                                    </Col>
                                </Row>
                            </Form>
                        </Col>
                    </Row>
                </Container>
            </section>
        </CommonLayout>
    )
}

export default ForgetPwd;